#include "mystdio.h"
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>



myFILE* my_fopen(const char *path, const char *mode) {
  int fd = 0;
  int flag = 0; // 标记文件的打开方式，之后传给系统调用
  if (strcmp(mode, "r") == 0) {
    flag |= O_RDONLY;
  } else if (strcmp(mode, "w") == 0) {
    flag |= (O_CREAT | O_TRUNC | O_WRONLY);
  } else if (strcmp(mode, "a") == 0) {
    flag |= (O_CREAT | O_WRONLY | O_APPEND);
  } 

  if (flag & O_CREAT) {
    fd = open(path, flag, 0666);
  } else {
    fd = open(path, flag);
  }

  if (fd < 0) {
    return NULL; // 就像C语言库中的一样，打开失败直接返回NULL
  }


  myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
  if (!fp) {
    return NULL;
  }
  fp->flag = FLUSH_LINE;
  fp->end = 0;
  fp->fileno = fd;
  return fp;

}

int my_fwrite(const char* s, int num, myFILE* stream) {
  memcpy(stream->buffer + stream->end, s, num);
  stream->end += num;

  // 判断是否需要进行行刷新
  if ((stream->flag & FLUSH_LINE) && stream->end > 0 && stream->buffer[stream->end - 1] == '\n') {
    my_fflush(stream);
  }
  return 0;
}
int my_fflush(myFILE* stream) {
  if (stream->end > 0) {
    write(stream->fileno, stream->buffer, stream->end);
    // 再将缓冲区内的数据“清空”
    stream->end = 0;
  }
  return 0;
}


int my_fclose(myFILE* stream) {
  // 关闭前先刷新缓冲区
  my_fflush(stream);
  close(stream->fileno);
  free(stream);
  return 0;
}
